﻿using Compass.Wasm.Shared.Params;
using System.Collections.Generic;

namespace Compass.Wpf.ViewModels;

public class PackingInfoViewModel : NavigationViewModel
{
    #region ctor
    private readonly IPackingListService _packingListService;
    private readonly IPalletService _palletService;

    private readonly IPrintsService _printsService;
    public PackingInfoViewModel(IContainerProvider provider) : base(provider)
    {
        _packingListService = provider.Resolve<IPackingListService>();
        _palletService = provider.Resolve<IPalletService>();
        _printsService=provider.Resolve<IPrintsService>();
        PackingList = new PackingListDto();
        
        ExecuteCommand = new DelegateCommand<string>(Execute);
        DeleteItem = new DelegateCommand<PalletDto>(DeletePallet);
        IsEnable = true;
        UpdateRoles = "admin,prod,pmc,pm,dsr";
        PrintLabelRoles = "admin,whse";
        BatchRoles = "admin";
        SupperUpdateRoles = "admin,pm,dsr";
    }
    public DelegateCommand<string> ExecuteCommand { get; }
    public DelegateCommand<PalletDto> DeleteItem { get; }
    #endregion

    #region 角色控制属性
    private string updateRoles;
    public string UpdateRoles
    {
        get => updateRoles;
        set { updateRoles = value; RaisePropertyChanged(); }
    }
    private string supperUpdateRoles;
    public string SupperUpdateRoles
    {
        get => supperUpdateRoles;
        set { supperUpdateRoles = value; RaisePropertyChanged(); }
    }
    private string printLabelRoles;
    public string PrintLabelRoles
    {
        get => printLabelRoles;
        set { printLabelRoles = value; RaisePropertyChanged(); }
    }
    private string batchRoles;
    public string BatchRoles
    {
        get => batchRoles;
        set { batchRoles = value; RaisePropertyChanged(); }
    }

    #endregion

    #region 属性
    private bool isEnable;
    public bool IsEnable
    {
        get => isEnable;
        set { isEnable = value; RaisePropertyChanged(); }
    }
    
    public PackingListParam? PklParam { get; set; }
    
    private PackingListDto packingList;
    public PackingListDto PackingList
    {
        get => packingList;
        set { packingList = value; RaisePropertyChanged(); }
    }

    public ObservableRangeCollection<PalletDto> PalletDtos { get; } = new();
    
    public bool? IsAllItemsSelected
    {
        get
        {
            var selected = PalletDtos.Select(item => item.IsSelected).Distinct().ToList();
            return selected.Count == 1 ? selected.Single() : null;
        }
        set
        {
            if (value.HasValue)
            {
                SelectAll(value.Value, PalletDtos);
                RaisePropertyChanged();
            }
        }
    }
    private static void SelectAll(bool select, IEnumerable<PalletDto> items)
    {
        foreach (var item in items)
        {
            item.IsSelected = select;
        }
    }
    #endregion

    #region 执行操作
    private async void Execute(string obj)
    {
        switch (obj)
        {
            case "PackingList": PackingListNavigate(); break;
            case "Add": Add(); break;
            case "Save":await Save(); break;
            case "ExportPackingInfo": await ExportPackingInfo(); break;
            case "PrintLabel":await PrintLabel();break;
            case "ExportWoodExcel": await ExportWoodExcel();break;
            case "BatchWarehousing":await BatchWarehousing(); break;
            case "BatchShipping": await BatchShipping();break;
            case "ForceDelete": await ForceDelete();break;
        }
    }
    
    /// <summary>
    /// 导航到装箱清单
    /// </summary>
    private void PackingListNavigate()
    {
        var packingListParam = new PackingListParam
        {
            ProjectId = PackingList.ProjectId,
            Batch = PackingList.Batch
        };
        var param = new NavigationParameters { { "Value", packingListParam } };
        RegionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate("PackingListView", back =>
        {
            Journal = back.Context.NavigationService.Journal;
        }, param);
    }

    /// <summary>
    /// 添加自定义托盘（配件或者是天花）
    /// </summary>
    private void Add()
    {
        PalletDtos.Add(new PalletDto()
        {
            PalletNumber = PalletDtos.Max(x => x.PalletNumber) is null ? 1 : PalletDtos.Max(x => x.PalletNumber)+1,
            MainPlanId = PackingList.Id,
            ShowItem = false,
            IsSelected = false
        });

        Aggregator.SendMessage("已添加行，请使用滚轮定位到最后一行填写信息！");

        //弹窗添加信息?
    }

    /// <summary>
    /// 删除条目
    /// </summary>
    private async void DeletePallet(PalletDto obj)
    {
        //删除询问
        var dialogResult = await DialogHost.Question("删除确认", $"确认删除：{obj.PalletNumber}号托盘【{obj.MtlNumber}】吗?");
        if (dialogResult.Result != ButtonResult.OK) return;

        if (obj.Id != null && obj.Id != Guid.Empty)
        {
            //从数据库删除
           await _palletService.DeleteAsync(obj.Id.Value);
        }
        PalletDtos.Remove(obj);
        Aggregator.SendMessage("删除托盘信息完成！");
    }

    /// <summary>
    /// 保存信息
    /// </summary>
    private async Task Save()
    {
        //检查是否有重复的托盘，提示删除
        if (PalletDtos.GroupBy(x => x.PalletNumber).Any(x => x.Count() > 1))
        {
            await DialogHost.Question("提示", "有重复的托盘号，请删除重复的托盘）");
            IsEnable = true;
            return;
        }

        foreach (var item in PalletDtos)
        {
            if (item.Id != null && item.Id != Guid.Empty)
            {
                //更新Pallet
                await _palletService.UpdateAsync(item.Id.Value, item);
            }
            else
            {
                //添加Pallet
                if (item.PalletNumber is null)
                {
                    //await DialogHost.Question("提示", "请填写托盘号，产品编号（用来描述产品,请勿重复）");
                    //必须要填写托盘号，空的就跳过，不添加
                    continue;
                }
                await _palletService.AddAsync(item);
            }
        }
        await GetDataAsync();
        Aggregator.SendMessage("装箱信息已保存！");
    }

    /// <summary>
    /// 导出装箱清单Excel到桌面
    /// </summary>
    private async Task ExportPackingInfo()
    {
        IsEnable = false;
        await Save();
        //导出Excel文件
        await  _printsService.ExportPackingInfoAsync(packingList,PalletDtos.ToList());
        IsEnable = true;
    }

    /// <summary>
    /// 打印托盘标签
    /// </summary>
    private async Task PrintLabel()
    {
        IsEnable = false;
        //打印询问
        var dialogResult = await DialogHost.Question("打印确认", "确认要打印标签吗?");
        if (dialogResult.Result != ButtonResult.OK)
        {
            IsEnable = true;
            return;
        }
        await Task.Delay(500);//防止卡屏

        //获取勾选的Item，并筛选托盘
        var selectItemDtos = PalletDtos.Where(x => x.IsSelected).ToList();
        if (selectItemDtos.Count == 0)
        {
            Aggregator.SendMessage("请勾选（或全选）要打印的托盘行！");
            IsEnable = true;
            return;
        }
        await _printsService.PrintPalletLabelAsync(PackingList.OdpNumber,selectItemDtos);
        Aggregator.SendMessage("打印标签完成！");
        IsEnable = true;
    }

    /// <summary>
    /// 导出消防木材统计表Excel到桌面
    /// </summary>
    private async Task ExportWoodExcel()
    {
        IsEnable = false;
        //导出Excel文件
        //await _printsService.ExportWoodInfoAsync(packingList);
        IsEnable = true;
    }

    #endregion


    #region 批量入库和出货（弹出提示框）
    private async Task BatchWarehousing()
    {
        //弹窗选择日期
        var dialogResult = await DialogHost.AskDataAndLocation("请选择入库日期和库位", DateTime.Now,WarehouseLocation_e.B7车间);

        if (dialogResult.Result != ButtonResult.OK) return;

        var date = dialogResult.Parameters.ContainsKey("Date")? dialogResult.Parameters.GetValue<DateTime>("Date"): DateTime.Now;
        var location= dialogResult.Parameters.ContainsKey("Location") ? dialogResult.Parameters.GetValue<WarehouseLocation_e>("Location") : WarehouseLocation_e.B7车间;

        foreach (var item in PalletDtos)
        {
            item.WarehousingTime= date;
            item.Location= location;
            await _palletService.UpdateStatusesAsync(item.Id.Value, item);
        }
        Aggregator.SendMessage("批量入库已完成！");
    }

    private async Task BatchShipping()
    {
        //弹窗选择日期
        var dialogResult = await DialogHost.AskData("请选择入库日期和库位", DateTime.Now);

        if (dialogResult.Result != ButtonResult.OK) return;

        var date = dialogResult.Parameters.ContainsKey("Date") ? dialogResult.Parameters.GetValue<DateTime>("Date") : DateTime.Now;

        foreach (var item in PalletDtos)
        {
            item.ShippingTime= date;
            await _palletService.UpdateStatusesAsync(item.Id.Value, item);
        }
        Aggregator.SendMessage("批量出货已完成！");
    }
    //ForceDelete
    private async Task ForceDelete()
    {
        var selectItemDtos = PalletDtos.Where(x => x.IsSelected).ToList();
        if (selectItemDtos.Count == 0)
        {
            Aggregator.SendMessage("请勾选（或全选）要强制删除的托盘！");
            return;
        }
        //删除询问
        var dialogResult = await DialogHost.Question("删除确认", "确认要强制删除吗?");
        if (dialogResult.Result != ButtonResult.OK) return;
        
        foreach (var item in selectItemDtos)
        {
            await _palletService.DeleteAsync(item.Id.Value);
            PalletDtos.Remove(item);
        }
        Aggregator.SendMessage("强制删除已完成！");
    }
    #endregion
    
    #region 初始化
    private async Task GetDataAsync()
    {
        //根据项目ID和分批获取装箱信息表
        var pklResponse = await _packingListService.GetPackingInfoAsync(PklParam);
        if (pklResponse.Status)
        {
            PackingList = pklResponse.Result;
            var palletResponse = await _palletService.GetAllByMainPlanIdAsync(PackingList.Id.Value);
            if (pklResponse.Status)
            {
                PalletDtos.ReplaceRange(palletResponse.Result);
                //绑定勾选数据变更
                foreach (var item in PalletDtos)
                {
                    item.PropertyChanged += (sender, args) =>
                    {
                        if (args.PropertyName == nameof(ModuleDto.IsSelected))
                            RaisePropertyChanged(nameof(IsAllItemsSelected));
                    };
                }
                IsAllItemsSelected = false;
            }
        }
        else
        {
            Aggregator.SendMessage("技术部还没出装箱清单！");
            //返回到主计划页面
            RegionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate("MainPlansView", back =>
            {
                Journal = back.Context.NavigationService.Journal;
            });
        }
        
    }
    
    public override async void OnNavigatedTo(NavigationContext navigationContext)
    {
        base.OnNavigatedTo(navigationContext);
        PklParam = navigationContext.Parameters.ContainsKey("Value") ?
            navigationContext.Parameters.GetValue<PackingListParam>("Value")
            : null;
        if(PklParam != null) { await GetDataAsync(); }
    }
    #endregion
}